<?php
declare(strict_types=1);

namespace App\Common\Middleware;

use App\User\Service\UserService;
use Donjan\Permission\Models\Permission;
use Hyperf\Contract\ConfigInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class PermissionMiddleware implements MiddlewareInterface
{
    /**
     * @Inject
     * @var ConfigInterface
     */
    protected $config;

    /**
     * @Inject
     * @var UserService
     */
    protected $userService;

    /**
     * @Inject
     * @var RequestInterface
     */
    protected $requestion;

    /**
     * @var HttpResponse
     */
    protected $response;

    public function __construct(HttpResponse $response)
    {
        $this->response = $response;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
//        $user = $this -> userService->getCurrentInfo();
//        if($user['username'] == 'admin'){
//            return $handler->handle($request);
//        }
//        //去掉路由参数
//        $path = $this->requestion->path();
//        $path = strtolower($path); // 当前接口的请求地址，如： v1/user/current
//        // TODO 需要在权限表里面将URL字段改为当权接口地址。
//        $permission = Permission::where(['url' => $path])->value('name');
//        $res = $user -> can($permission);   // 验证用户是否有该权限
//        if(!$res){
//            $data = [
//                'code' => 101,
//                'msg' => '无权进行此操作！',
//                'data' => [],
//            ];
//            return $this->response->json($data);
//        }
        return $handler->handle($request);
    }

}
